const fs = require('fs')
const expect = require('chai').expect
let apiTest = function () {}

// 获取token
apiTest.getToken = function  () {
  return fs.readFileSync('test/token', {encoding: 'utf8'})
}

// 获取token
apiTest.getCookies = function  (res) {
  const Cookie = require('simple-cookie')
  var arr = []
  expect(res.headers['set-cookie']).to.be.an('array')
  res.headers['set-cookie'].forEach(function (v) {
    var cookie = Cookie.parse(v)
    arr.push(cookie)
  })
  return arr
}

// 合并公共请求参数
apiTest.unitGet = function (o) {
  return Object.assign({token: apiTest.getToken()}, o || {})
}

// 获取正常请求对象
apiTest.apiOk = function (res) {
  var json = res.data
  expect(json).to.be.an('object')
  expect(json.code).to.equal(30000, '接口返回错误码')
  expect(json).to.have.property('data')
  expect(json).to.not.have.property('error')
  expect(json.data).to.be.a('object')
  return json.data
}

// 获取错误请求对象
apiTest.apiErr = function (res, code) {
  var json = res.data
  expect(json).to.be.an('object')
  expect(json.code).to.be.a('number').to.not.equal(30000)
  if (code) expect(json.code).to.equal(code)
  expect(json).to.have.property('error').to.be.a('object')
  expect(json).to.not.have.property('data')
  expect(json.error).to.be.ok
  return json.error
}

apiTest.isObjectId = function (str) {
  expect(str).to.match(/^[0-9a-f]{24}$/)
}

apiTest.isIp = function (str) {
  expect(str).to.match(/^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/)
}

apiTest.random = function(min, max) {
  var dx = max - min
  var Rand = Math.random()
  var num = min + Math.round(Rand * dx) //四舍五入
  return num
}

// 随机取数组中的n个
apiTest.ranArr = function(arr, min, max) {
  var arrs = Object.assign([], arr)
  var num = min
  if (max) num = apiTest.random(min, max)
  var nrr = []
  for (var i = 0; i < num; i++) {
    var pid = apiTest.random(0, arrs.length - 1)
    nrr.push(arrs[pid])
    arrs.splice(pid, 1)
  }
  return nrr
}


module.exports = apiTest
